package com.weasel.http.helper;

import com.weasel.helper.DocumentConverter;
import com.weasel.helper.JsonHelper;
import com.weasel.http.adapter.ResponseAdapter;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;

/**
 * Created by Dylan on 2015/9/29.
 */
public final class HttpResponseHelper {


    /**将响应体为json的转化为entity
     * @param response http 响应
     * @param clazz 要转换为该类型
     * @return
     * @throws IOException
     */
    public static <T> T jsonResponseToEntity(HttpResponse response,Class<T> clazz) throws IOException {

        String json = getResponseString(response);
        return JsonHelper.fromJsonString(json,clazz);
    }

    /**将响应体为json的转化为entity
     * @param response http 响应
     * @param clazz 要转换为该类型
     * @param adapter 响应字符串替换
     * @return
     * @throws IOException
     */
    public static <T> T jsonResponseToEntity(HttpResponse response,Class<T> clazz,ResponseAdapter adapter) throws IOException {

        String json = getResponseString(response);
        json = adapter.adapter(json);
        return JsonHelper.fromJsonString(json,clazz);
    }

    /**将响应体为xml的转化为entity
     * @param response http 响应
     * @param clazz 要转换为该类型
     * @return
     * @throws IOException
     */
    public static <T> T xmlResponseToEntity(HttpResponse response,Class<T> clazz) throws IOException {

       return DocumentConverter.xmlToEntity(getResponseString(response), clazz);
    }

    /**将响应体为xml的转化为entity
     * @param response http 响应
     * @param clazz   要转换为该类型
     * @param adapter  响应字符串替换
     * @return
     * @throws IOException
     */
    public static <T> T xmlResponseToEntity(HttpResponse response,Class<T> clazz,ResponseAdapter adapter) throws IOException {

        String xml = getResponseString(response);
        xml = adapter.adapter(xml);
        return DocumentConverter.xmlToEntity(xml,clazz);
    }

    public static String getResponseString(HttpResponse response) throws IOException {

        final HttpEntity entity = response.getEntity();
        Charset charset = ContentType.getOrDefault(entity).getCharset();
        if(null == charset){
            charset = Consts.UTF_8;
        }
        return EntityUtils.toString(entity, charset);
    }

    private HttpResponseHelper() {
    }
}
